package org.club.Service.impl;

import lombok.extern.slf4j.Slf4j;
import org.club.Service.PublicService;
import org.club.Service.FileOssService;
import org.club.mapper.PublicMapper;
import org.club.common.model.dto.UsersDto;
import org.club.common.model.entity.BusinessException;
import org.club.common.model.entity.User;
import org.club.common.model.vo.UserVo;
import org.club.common.util.JwtUtil;
import org.club.common.util.RedisCacheHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.club.common.config.SecurityConfig;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

@Service
@Slf4j
public class PublicServiceImpl implements PublicService {
    @Autowired
    private SecurityConfig securityConfig;
    @Autowired
    private PublicMapper publicMapper;
    @Autowired
    private FileOssService fileOssService;//文件上传
    @Autowired
    private RedisCacheHelper redisCacheHelper;//Redis
    @Autowired
    private JwtUtil jwtUtil;

    //注册
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer registerWithAvatar(UsersDto userDto, MultipartFile file) {
        //验证参数有效性
        if (userDto.getUsername() == null || userDto.getPassword() == null || file.isEmpty()) {
            return 0;
        }
        try {
            //验证验证码
            redisCacheHelper.validateVerifyCode(userDto.getCodekey(), userDto.getCode());
        }catch (BusinessException e){
            throw new BusinessException(400, "验证码错误");
        }
        //验证用户名是否已存在
        if (publicMapper.select(userDto.getUsername()) != null) {
           throw new BusinessException(400, "用户名已存在");
        }
        //验证手机号是否存在
        if (publicMapper.selectPhone(userDto.getPhone())!=0){
            throw new BusinessException(400, "手机号已存在");
        }
        //上传图片获取图片路径
        String FileUrl = fileOssService.uploadToOss(file);
        userDto.setAvatarUrl(FileUrl);
        try {
            //将UsersDto对象转换为User对象
            User user = new User(userDto);
            user.setPassword(securityConfig.passwordEncoder().encode(userDto.getPassword()));
            Integer i = publicMapper.registerWithAvatar(user);
            //设置权限为普通用户
            publicMapper.setuser_roles(user.getId(), 3);
            return i;
        }catch (Exception e){
            e.printStackTrace();
            fileOssService.deleteFileFromOss(FileUrl);
            throw new BusinessException(500, "注册失败，数据一致性错误");
        }
    }
    //登录
    @Override
    public UserVo login(UsersDto userDto) {
        if (userDto.getUsername() == null || userDto.getPassword() == null) {
            return null;
        }
        //验证验证码
        try {
            redisCacheHelper.validateVerifyCode(userDto.getCodekey(), userDto.getCode());
        }catch (BusinessException e){
            e.printStackTrace();
            throw new BusinessException(400, "验证码错误");
        }
        //查询用户信息
        User user = publicMapper.login(userDto.getUsername());
        log.info("根据用户名查询出的用户信息"+user);
        if (user == null){
            throw new BusinessException(400, "未找到该用户");
        }
        //比较密码
        if (securityConfig.passwordEncoder().matches(userDto.getPassword(), user.getPassword())) {
            //登录成功
            UserVo userVo = new UserVo(user);
            String token = jwtUtil.generateToken(user.getUsername());
            userVo.setToken(token);
            String role = publicMapper.selectUser_roles(user.getId());
            userVo.setRole(role);
            return userVo;
        }else {
            throw new BusinessException(400, "密码错误");
        }
    }
    //重置密码
    @Override
    public Integer resetPassword(UsersDto userDto) {
        log.info("重置密码的参数"+userDto);
        if (userDto.getUsername() == null || userDto.getPhone() == null) {
            throw new BusinessException(400,"信息不完整");
        }
        try {
            redisCacheHelper.validateVerifyCode(userDto.getCodekey(), userDto.getCode());
        }catch (BusinessException e){
            e.printStackTrace();
            throw new BusinessException(400, "验证码错误");
        }
        User user = publicMapper.select(userDto.getUsername());
        System.out.println("user"+user);
        if (user != null && user.getPhone().equals(userDto.getPhone()) && user.getIdCard().equals
                (userDto.getId_card()) && user.getRealName().equals(userDto.getReal_name())) {
            String updatedPasswords = securityConfig.passwordEncoder().encode(userDto.getPassword());
            Integer i = publicMapper.update(updatedPasswords, userDto.getUsername());
            if (i > 0){
                return i;
            }else {
                throw new BusinessException(400, "重置密码失败");
            }
        }
        return 0;
    }
}
